package com.itheima.tliasmanager.interceptor;

import com.itheima.tliasmanager.utils.ApplicationContext;
import com.itheima.tliasmanager.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取令牌
        String token = request.getHeader("token");
        if (token == null){
            log.info("LoginInterceptor 拦截请求: 没有令牌, 直接封装未授权响应结果");
            // 令牌为空 响应未授权  (设置响应401: 未授权,前端统一处理 401 响应码,直接跳转到登陆界面)
            response.setStatus(401);
            return false;
        }

        // 令牌不为空
        try {
            Claims claims = JwtUtils.parseJWT(token);

            Integer id = (Integer) claims.get("id");
            // 将员工id保存到当前线程中
            ApplicationContext.setEmpId(id);
        }catch (Exception e){
            log.info("LoginInterceptor 拦截请求:  令牌无效, 直接封装未授权响应结果");
            response.setStatus(401);
            return false;
        }

        log.info("LoginInterceptor  拦截请求: 令牌有效，放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ApplicationContext.clear();
    }
}
